import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/userStore'
import router from '@/router'
// axios请求交互基础封装
import axios from 'axios'

// 创建axios实例
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  
  timeout: 10000
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  const userStore=useUserStore()
  if(userStore.userInfo.token){
    config.headers.Authorization=`Bearer ${userStore.userInfo.token}`
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  const userStore=useUserStore()
  // 统一普通错误提示
  ElMessage.warning(e.response.data.message)
  // 401特殊错误处理（token失效等问题）
  // 1.清空失效的用户数据
  // 2.跳转到登录页
  // 3.提示用户
  if(e.response.status===401){
    userStore.clearUserInfo()
    router.push('/login')
    ElMessage.error('请重新登录')
  }

  return Promise.reject(e)
})


export default httpInstance